package com.firsteapps.mobile.android.puzzle;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.firsteapps.mobile.android.puzzle.game.Helper;
import com.firsteapps.mobile.android.puzzle.game.PuzzleInfo;
import com.firsteapps.mobile.android.puzzle.game.TakePhotoActivity;
import com.firsteapps.mobile.android.puzzle.util.Consts;

public class CreatePuzzle extends PostLoginBase {

	private ImageView size_3, size_4, size_5, size_6, size_7, size_8, timeIncr, timeDecr, timeInfinite, movesIncr, movesDecr,
			movesInfinite, attemptsIncr, attemptsDecr, attemptsInfinite;
	private TextView timeLimit, movesLimit, attemptsLimit, autosolveYes, autosolveNo, alternativeImageYes, alternativeImageNo,
			alternativeTextYes, alternativeTextNo, imagePathPuzzle, imagePathAlternative;
	private ClickListener cpClickListener;
	private String puzzleImageName = null, alternativeImageName = null, alternativeText = null;
	private int puzzleSize = 3, maxMoves = -1, maxTime = -1, maxAttempts = -1;
	private boolean autoSolveEnabled = true, alternativeImageIncluded = false, alternativeTextIncluded = false;
	private EditText hiddenText;
	private String createdInfoPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_puzzle);

		cpClickListener = new ClickListener();
		size_3 = (ImageView) findViewById(R.id.cp_size_3_3);
		size_4 = (ImageView) findViewById(R.id.cp_size_4_4);
		size_5 = (ImageView) findViewById(R.id.cp_size_5_5);
		size_6 = (ImageView) findViewById(R.id.cp_size_6_6);
		size_7 = (ImageView) findViewById(R.id.cp_size_7_7);
		size_8 = (ImageView) findViewById(R.id.cp_size_8_8);
		size_3.setOnClickListener(cpClickListener);
		size_4.setOnClickListener(cpClickListener);
		size_5.setOnClickListener(cpClickListener);
		size_6.setOnClickListener(cpClickListener);
		size_7.setOnClickListener(cpClickListener);
		size_8.setOnClickListener(cpClickListener);

		timeIncr = (ImageView) findViewById(R.id.cp_time_limit_plus);
		timeDecr = (ImageView) findViewById(R.id.cp_time_limit_minus);
		timeInfinite = (ImageView) findViewById(R.id.cp_time_limit_infinity);
		timeIncr.setOnClickListener(cpClickListener);
		timeDecr.setOnClickListener(cpClickListener);
		timeInfinite.setOnClickListener(cpClickListener);
		timeLimit = (TextView) findViewById(R.id.cp_time_limit);
		timeLimit.setTextColor(Color.rgb(232, 232, 232));

		movesIncr = (ImageView) findViewById(R.id.cp_num_moves_plus);
		movesDecr = (ImageView) findViewById(R.id.cp_num_moves_minus);
		movesInfinite = (ImageView) findViewById(R.id.cp_num_moves_infinity);
		movesIncr.setOnClickListener(cpClickListener);
		movesDecr.setOnClickListener(cpClickListener);
		movesInfinite.setOnClickListener(cpClickListener);
		movesLimit = (TextView) findViewById(R.id.cp_moves_limit);
		movesLimit.setTextColor(Color.rgb(232, 232, 232));

		attemptsIncr = (ImageView) findViewById(R.id.cp_num_attempts_plus);
		attemptsDecr = (ImageView) findViewById(R.id.cp_num_attempts_minus);
		attemptsInfinite = (ImageView) findViewById(R.id.cp_num_attempts_infinity);
		attemptsIncr.setOnClickListener(cpClickListener);
		attemptsDecr.setOnClickListener(cpClickListener);
		attemptsInfinite.setOnClickListener(cpClickListener);
		attemptsLimit = (TextView) findViewById(R.id.cp_attempts_limit);
		attemptsLimit.setTextColor(Color.rgb(232, 232, 232));

		autosolveYes = (TextView) findViewById(R.id.cp_yes_autosolve);
		autosolveYes.setOnClickListener(cpClickListener);
		autosolveNo = (TextView) findViewById(R.id.cp_not_autosolve);
		autosolveNo.setOnClickListener(cpClickListener);
		alternativeImageYes = (TextView) findViewById(R.id.cp_yes_alternative_image);
		alternativeImageYes.setOnClickListener(cpClickListener);
		alternativeImageNo = (TextView) findViewById(R.id.cp_not_alternative_image);
		alternativeImageNo.setOnClickListener(cpClickListener);
		alternativeTextYes = (TextView) findViewById(R.id.cp_yes_hidden_text);
		alternativeTextYes.setOnClickListener(cpClickListener);
		alternativeTextNo = (TextView) findViewById(R.id.cp_not_hidden_text);
		alternativeTextNo.setOnClickListener(cpClickListener);

		hiddenText = (EditText) findViewById(R.id.cp_input_hidden_text);
		hiddenText.setTag(hiddenText.getKeyListener());
		hiddenText.setBackgroundDrawable(null);
		hiddenText.setKeyListener(null);

		findViewById(R.id.cp_camera_top).setOnClickListener(cpClickListener);
		findViewById(R.id.cp_folder_top).setOnClickListener(cpClickListener);

		imagePathPuzzle = (TextView) findViewById(R.id.cp_picture_path_top);
		imagePathAlternative = (TextView) findViewById(R.id.cp_picture_path_bottom);

		ImageView createButton = (ImageView) findViewById(R.id.cp_create);
		createButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (puzzleImageName == null) {
					Helper.doMessageDialog(CreatePuzzle.this, "CREATION PROBLEM", "No image is selected for puzzle");
				} else {
					AlertDialog dialog = new AlertDialog.Builder(CreatePuzzle.this).setTitle("Create Puzzle")
							.setMessage("Are you sure you want to create the puzzle?")
							.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									PuzzleInfo info = createInfo();
									if (info != null) {
										Intent create = new Intent(CreatePuzzle.this, PostLogin.class);
										create.putExtra(Consts.PUZZLE_KEY, info);
										startActivity(create);
										finish();
										overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
									}
								}
							}).setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							}).create();
					dialog.show();
				}
			}
		});

		findViewById(R.id.cp_share).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (puzzleImageName == null) {
					Helper.doMessageDialog(CreatePuzzle.this, "Share puzzle", "No puzzle is created to share");
				} else {
					PuzzleInfo info = createInfo();
					if (info != null)
						Helper.shareCurrentPuzzle(CreatePuzzle.this, createdInfoPath, info);
				}
			}
		});
	}

	private PuzzleInfo createInfo() {
		maxTime = timeLimit.getCurrentTextColor() == getResources().getColor(R.color.text_selected) ? Integer.parseInt(timeLimit
				.getText().toString()) : -1;
		maxMoves = movesLimit.getCurrentTextColor() == getResources().getColor(R.color.text_selected) ? Integer
				.parseInt(movesLimit.getText().toString()) : -1;
		maxAttempts = attemptsLimit.getCurrentTextColor() == getResources().getColor(R.color.text_selected) ? Integer
				.parseInt(attemptsLimit.getText().toString()) : -1;
		PuzzleInfo info = new PuzzleInfo(puzzleImageName, puzzleSize, maxTime, maxMoves, maxAttempts, autoSolveEnabled);
		if (alternativeImageIncluded && alternativeImageName != null)
			info.setAlternativeImage(alternativeImageName);

		if (alternativeTextIncluded) {
			alternativeText = hiddenText.getText() == null ? null : hiddenText.getText().toString();
			if (alternativeText != null)
				info.setAlternativeText(alternativeText);
		}

		if (Helper.registerPuzzle(CreatePuzzle.this, Consts.FOLDER_NAME_REGISTERED_PUZZLES, info.getPuzzleId())) {
			createdInfoPath = Helper.saveCreatedPuzzle(CreatePuzzle.this, info, getWorkingDirectory()
					+ Consts.FOLDER_NAME_CREATED);
			return info;
		} else {
			Helper.doMessageDialog(CreatePuzzle.this, "CREATION PROBLEM", "Unable to save the puzzle");
			return null;
		}
	}

	private class ClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.cp_size_3_3:
				resetSizeBackgrounds(v);
				puzzleSize = 3;
				movesLimit.setText("120");
				timeLimit.setText("120");
				break;
			case R.id.cp_size_4_4:
				resetSizeBackgrounds(v);
				puzzleSize = 4;
				movesLimit.setText("180");
				timeLimit.setText("180");
				break;
			case R.id.cp_size_5_5:
				resetSizeBackgrounds(v);
				puzzleSize = 5;
				movesLimit.setText("240");
				timeLimit.setText("240");
				break;
			case R.id.cp_size_6_6:
				resetSizeBackgrounds(v);
				puzzleSize = 6;
				movesLimit.setText("480");
				timeLimit.setText("480");
				break;
			case R.id.cp_size_7_7:
				resetSizeBackgrounds(v);
				puzzleSize = 7;
				movesLimit.setText("960");
				timeLimit.setText("960");
				break;
			case R.id.cp_size_8_8:
				resetSizeBackgrounds(v);
				puzzleSize = 8;
				movesLimit.setText("1800");
				timeLimit.setText("1800");
				break;
			case R.id.cp_num_moves_plus:
				maxMoves = movesLimit.getText() == null ? 0 : Integer.parseInt(movesLimit.getText().toString());
				maxMoves++;
				movesLimit.setText("" + maxMoves);
				movesLimit.setTextColor(getResources().getColor(R.color.text_selected));
				movesInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_num_moves_minus:
				maxMoves = movesLimit.getText() == null ? 0 : Integer.parseInt(movesLimit.getText().toString());
				maxMoves = maxMoves < 1 ? 0 : maxMoves - 1;
				movesLimit.setText("" + maxMoves);
				movesLimit.setTextColor(getResources().getColor(R.color.text_selected));
				movesInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_num_moves_infinity:
				movesLimit.setTextColor(getResources().getColor(R.color.text_not_selected));
				movesInfinite.setBackgroundResource(R.drawable.shape_selected_cp);
				maxMoves = -1;
				break;
			case R.id.cp_time_limit_minus:
				maxTime = timeLimit.getText() == null ? 0 : Integer.parseInt(timeLimit.getText().toString());
				maxTime = maxTime < 10 ? 0 : maxTime - 10;
				timeLimit.setText("" + maxTime);
				timeLimit.setTextColor(getResources().getColor(R.color.text_selected));
				timeInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_time_limit_plus:
				maxTime = timeLimit.getText() == null ? 0 : Integer.parseInt(timeLimit.getText().toString());
				maxTime += 10;
				timeLimit.setText("" + maxTime);
				timeLimit.setTextColor(getResources().getColor(R.color.text_selected));
				timeInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_time_limit_infinity:
				timeLimit.setTextColor(getResources().getColor(R.color.text_not_selected));
				timeInfinite.setBackgroundResource(R.drawable.shape_selected_cp);
				maxTime = -1;
				break;
			case R.id.cp_num_attempts_plus:
				maxAttempts = attemptsLimit.getText() == null ? 0 : Integer.parseInt(attemptsLimit.getText().toString());
				maxAttempts++;
				attemptsLimit.setText("" + maxAttempts);
				attemptsLimit.setTextColor(getResources().getColor(R.color.text_selected));
				attemptsInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_num_attempts_minus:
				maxAttempts = attemptsLimit.getText() == null ? 0 : Integer.parseInt(attemptsLimit.getText().toString());
				maxAttempts = maxAttempts < 1 ? 0 : maxAttempts - 1;
				attemptsLimit.setText("" + maxAttempts);
				attemptsLimit.setTextColor(getResources().getColor(R.color.text_selected));
				attemptsInfinite.setBackgroundDrawable(null);
				break;
			case R.id.cp_num_attempts_infinity:
				attemptsLimit.setTextColor(getResources().getColor(R.color.text_not_selected));
				attemptsInfinite.setBackgroundResource(R.drawable.shape_selected_cp);
				maxAttempts = -1;
				break;
			case R.id.cp_yes_autosolve:
				autosolveYes.setBackgroundResource(R.drawable.shape_selected_cp);
				autosolveNo.setBackgroundDrawable(null);
				autoSolveEnabled = true;
				break;
			case R.id.cp_not_autosolve:
				autosolveNo.setBackgroundResource(R.drawable.shape_selected_cp);
				autosolveYes.setBackgroundDrawable(null);
				autoSolveEnabled = false;
				break;
			case R.id.cp_yes_alternative_image:
				alternativeImageYes.setBackgroundResource(R.drawable.shape_selected_cp);
				alternativeImageNo.setBackgroundDrawable(null);
				findViewById(R.id.cp_camera_bottom).setOnClickListener(cpClickListener);
				findViewById(R.id.cp_folder_bottom).setOnClickListener(cpClickListener);
				alternativeImageIncluded = true;
				break;
			case R.id.cp_not_alternative_image:
				alternativeImageNo.setBackgroundResource(R.drawable.shape_selected_cp);
				alternativeImageYes.setBackgroundDrawable(null);
				findViewById(R.id.cp_camera_bottom).setOnClickListener(null);
				findViewById(R.id.cp_folder_bottom).setOnClickListener(null);
				alternativeImageIncluded = false;
				break;
			case R.id.cp_yes_hidden_text:
				alternativeTextYes.setBackgroundResource(R.drawable.shape_selected_small);
				alternativeTextNo.setBackgroundDrawable(null);
				hiddenText.setKeyListener((KeyListener) hiddenText.getTag());
				alternativeTextIncluded = true;
				break;
			case R.id.cp_not_hidden_text:
				alternativeTextNo.setBackgroundResource(R.drawable.shape_selected_small);
				alternativeTextYes.setBackgroundDrawable(null);
				hiddenText.setKeyListener(null);
				alternativeTextIncluded = false;
				break;
			case R.id.cp_camera_top:
				Intent capturePuzzle = new Intent(CreatePuzzle.this, TakePhotoActivity.class);
				capturePuzzle.putExtra(Consts.SELECT_IMAGE, Consts.CAPTURE_PUZZLE_REQUEST_CODE);
				capturePuzzle.putExtra(Consts.SAVE_IMAGE_TO, getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED));
				startActivityForResult(capturePuzzle, Consts.CAPTURE_PUZZLE_REQUEST_CODE);
				overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
				break;
			case R.id.cp_folder_top:
				Intent selectPuzzle = new Intent(Intent.ACTION_GET_CONTENT);
				selectPuzzle.setType("image/*");

				startActivityForResult(Intent.createChooser(selectPuzzle, "Select Image"),
						Consts.SELECT_PUZZLE_GALLERY_REQUEST_CODE);
				break;
			case R.id.cp_camera_bottom:
				if (alternativeImageIncluded) {
					Intent captureAlternative = new Intent(CreatePuzzle.this, TakePhotoActivity.class);
					captureAlternative.putExtra(Consts.SELECT_IMAGE, Consts.CAPTURE_ALTERNATIVE_REQUEST_CODE);
					captureAlternative.putExtra(Consts.SAVE_IMAGE_TO, getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED));
					startActivityForResult(captureAlternative, Consts.CAPTURE_ALTERNATIVE_REQUEST_CODE);
					overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
				}
				break;
			case R.id.cp_folder_bottom:
				Intent selectAlternative = new Intent(Intent.ACTION_GET_CONTENT);
				selectAlternative.setType("image/*");

				startActivityForResult(Intent.createChooser(selectAlternative, "Select Image"),
						Consts.SELECT_ALTERNATIVE_GALLERY_REQUEST_CODE);
				break;
			default:
				break;
			}
		}
	}

	private void resetSizeBackgrounds(View v) {
		size_3.setBackgroundResource(R.drawable.size_not_selected_cp);
		size_4.setBackgroundResource(R.drawable.size_not_selected_cp);
		size_5.setBackgroundResource(R.drawable.size_not_selected_cp);
		size_6.setBackgroundResource(R.drawable.size_not_selected_cp);
		size_7.setBackgroundResource(R.drawable.size_not_selected_cp);
		size_8.setBackgroundResource(R.drawable.size_not_selected_cp);
		v.setBackgroundResource(R.drawable.size_selected_cp);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri uri = data.getData();
			if (requestCode == Consts.CAPTURE_PUZZLE_REQUEST_CODE) {
				puzzleImageName = uri.getPath();
				imagePathPuzzle.setText(puzzleImageName);
			}
			if (requestCode == Consts.CAPTURE_ALTERNATIVE_REQUEST_CODE) {
				alternativeImageName = uri.getPath();
				imagePathAlternative.setText(alternativeImageName);
			}
			if (requestCode == Consts.SELECT_PUZZLE_GALLERY_REQUEST_CODE) {
				Log.d("IMAGE URL", uri.toString());

				String[] imageAndOrient = Helper.getImageRealPathFromURI(uri, CreatePuzzle.this);
				if (imageAndOrient != null) {
					String imagePath = imageAndOrient[0];
					StringBuilder messages = new StringBuilder();
					imagePathPuzzle.setText(imagePath);
					puzzleImageName = Helper.saveGalleryImage(CreatePuzzle.this, messages, imagePath,
							Consts.SELECT_PUZZLE_GALLERY_REQUEST_CODE, getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED));
					if (puzzleImageName == null)
						Helper.doMessageDialog(CreatePuzzle.this, getString(R.string.app_name),
								messages.length() > 0 ? messages.toString() : "Unable to pick the image.");
				}
			}
			if (requestCode == Consts.SELECT_ALTERNATIVE_GALLERY_REQUEST_CODE) {
				Log.d("IMAGE URL", uri.toString());

				String[] imageAndOrient = Helper.getImageRealPathFromURI(uri, CreatePuzzle.this);
				if (imageAndOrient != null) {
					String imagePath = imageAndOrient[0];
					StringBuilder messages = new StringBuilder();
					System.out.println("IMAGEPATH " + imagePath);
					imagePathAlternative.setText(imagePath);
					alternativeImageName = Helper.saveGalleryImage(CreatePuzzle.this, messages, imagePath,
							Consts.SELECT_ALTERNATIVE_GALLERY_REQUEST_CODE, getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED));
					if (alternativeImageName == null)
						Helper.doMessageDialog(CreatePuzzle.this, getString(R.string.app_name),
								messages.length() > 0 ? messages.toString() : "Unable to pick the image.");
				}
			}
		}
	}
}
